package edu.sju.chenshu.common.security.service;

import edu.sju.chenshu.common.core.constants.CacheConstants;
import edu.sju.chenshu.common.core.constants.Constants;
import edu.sju.chenshu.common.core.constants.JwtConstants;
import edu.sju.chenshu.common.core.utils.JwtUtils;
import edu.sju.chenshu.common.core.utils.ThreadLocalUtil;
import edu.sju.chenshu.common.redis.service.RedisService;
import edu.sju.chenshu.common.core.domain.LoginUser;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//操作用户登录令牌的方法
@Service
@Slf4j
public class TokenService {
    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String jwtSecret,
                              Integer identity, String nickname, String headImage) {
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        String token = JwtUtils.createToken(claims, jwtSecret);

        //将key值存入redis
        String key = getTokenKey(userId.toString());
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickname);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        return token;
    }

    //身份认证后延长token有效时间 延长redis中tokenKey的有效时间  在拦截器中调用
    public void extendToken(String token, String secret){
        String userId = getUserId(token, secret);
        ThreadLocalUtil.set(Constants.USER_ID, Long.valueOf(userId));
        if (userId == null) {
            return;
        }
        String tokenKey = getTokenKey(userId);
        //剩余180分钟的时候进行延长
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != -2 && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userId = getUserId(token, secret);
        if (userId == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userId), LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {
        String userId = getUserId(token, secret);
        if (userId == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userId));
    }

    //拼接redis中的存储的tokenKey
    private String getTokenKey(String userId){
        return CacheConstants.LOGIN_TOKEN_KEY + userId;
    }

    //解析token中的userId
    public String getUserId(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token: {}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token: {}, 出现异常", token , e);
            return null;
        }
        return JwtUtils.getUserId(claims); //获取jwt中的key
    }

    public void refreshLoginUser(String nickName, String headImage, String userId) {
        String tokenKey = getTokenKey(userId);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
